import argparse
from model.net import CLSNet, CLSNet_Attention
from data.tvm_dataset import TVMAttrDataSet
import torch
import datetime
import os
from torch.utils.data import DataLoader
import tqdm
from loguru import logger
import sys
from my_utils.log_util import LogUtil
from sklearn.metrics import accuracy_score
import pickle

label_list = [
    'LSTM', 'UpSampling2D', 'UpSampling3D', 'Cropping2D', 'ZeroPadding2D', 'ZeroPadding3D', 'SeparableConv2D', 'Conv2D',
    'DepthwiseConv2D'
]


def run(args):
    # Create the results dir
    if not os.path.exists("./results"):
        os.mkdir("./results")

    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    current_time = datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S")

    LogUtil.create_dir(args, current_time, os.path.basename(sys.argv[0]))

    # Prepare Data
    train_dataset = TVMAttrDataSet(args.data,
                                   train_ratio=args.train_ratio if args.eval == 0 else 0.001,
                                   w2v_model=args.w2v_model,
                                   type=args.type,
                                   attr_name=args.attr_name,
                                   attr_idx=args.attr_idx,
                                   config_path=args.config_path,
                                   shape_info=(args.shape_info == 1),
                                   value_trace=True,
                                   weight_info=(args.weight_info == 1))
    test_dataset = TVMAttrDataSet(args.data,
                                  train_ratio=args.train_ratio,
                                  mode='test',
                                  w2v_model=args.w2v_model,
                                  type=args.type,
                                  attr_name=args.attr_name,
                                  attr_idx=args.attr_idx,
                                  config_path=args.config_path,
                                  shape_info=(args.shape_info == 1),
                                  value_trace=True,
                                  weight_info=(args.weight_info == 1))

    train_dataloader = DataLoader(train_dataset, batch_size=1, shuffle=True, pin_memory=True)
    test_dataloader = DataLoader(test_dataset, batch_size=1, shuffle=True, pin_memory=True)

    # Model Init
    net = CLSNet(in_d=200,
                 out_classes=args.num_class,
                 hiden=args.hsize,
                 num_layers=args.num_layers,
                 has_shape=(args.shape_info == 1),
                 has_value=True,
                 has_weight_info=(args.weight_info == 1))

    if args.attention == 1:
        net = CLSNet_Attention(in_d=200, out_classes=args.num_class, hiden=args.hsize, num_layers=args.num_layers)
    if not args.ckpt == "None":
        net.load_state_dict(torch.load(args.ckpt))
    net.to(device)

    # Init Optimizor
    optimizer = torch.optim.Adam(net.parameters(), lr=args.lr)
    if args.optim == "sgd":
        optimizer = torch.optim.SGD(net.parameters(), lr=args.lr)

    criterion = torch.nn.CrossEntropyLoss()

    failure_cases = []
    if args.eval == 1:
        net.eval()
        logger.info("Start evaluation ...")
        net.eval()
        preds = []
        targets = []
        for input, target, shape_info, value_data in tqdm.tqdm(test_dataloader):
            pred = net(input, device, shape_info=shape_info, value_data=value_data)
            if pred is None:
                continue
            pred = pred.detach().cpu()
            pred = pred[0].topk(1)[1][0]
            preds.append(pred.numpy())
            targets.append(target[0].numpy())
            logger.debug("Target: {},  Pred: {}".format(targets[-1], preds[-1]))

            if pred != target:
                failure_cases.append([pred, target, input])

        logger.info("Accuracy: {}".format(accuracy_score(targets, preds)))
        with open("failure_cases.pkl", "wb") as f:
            pickle.dump(failure_cases, f)
        exit(0)

    # Training
    for i in range(args.epochs):
        pbar = tqdm.tqdm(total=len(train_dataset))
        pbar.set_description("Epoch:{}, Loss:{}".format(i + 1, 0))
        count = 0
        sum_loss = 0
        net.train()
        for input, target, shape_info, value_data in train_dataloader:
            pbar.update(1)
            if len(input) == 0:
                continue
            pred = net(input, device, shape_info=shape_info, value_data=value_data)

            optimizer.zero_grad()

            loss = criterion(pred, target[0].to(device))
            loss.backward()
            optimizer.step()

            sum_loss += loss.item()
            count += 1

            if count % 10 == 0:
                pbar.set_description("Epoch:{}, Loss:{}".format(i + 1, sum_loss / count))
        pbar.close()
        logger.info("Epoch:{}, Loss:{}".format(i + 1, sum_loss / count))

        # Test
        if i % args.eval_per_epoch == 0 or i == (args.epochs - 1):
            save_path = "results/{}-({})/checkpoints/".format(current_time, os.path.basename(sys.argv[0]))
            torch.save(net.state_dict(), "{}/model_ckpt_{}.pth".format(save_path, i))
            logger.info("Start evaluation ...")
            net.eval()
            tmp_count = 0
            succ_count = 0
            pbar = tqdm.tqdm(total=len(test_dataset))
            for input, target, shape_info, value_data in test_dataloader:
                pbar.update(1)
                pred = net(input, device, shape_info=shape_info, value_data=value_data)
                if pred is None:
                    continue
                pred = pred[0].topk(1)[1][0]
                if pred == target[0].to(device):
                    succ_count += 1
                tmp_count += 1

            pbar.close()
            logger.info("Accuracy: {}".format(succ_count / tmp_count))

    logger.info("Finished!")


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='TVM Reversion')
    parser.add_argument("--epochs", default=200, type=int, help="number of epochs")
    parser.add_argument("--lr", default=1e-4, type=float, help="Learning rate")
    parser.add_argument("--hsize", default=200, type=int, help="hidden size of lstm")
    parser.add_argument("--num_layers", default=2, type=int, help="layers of lstm")
    parser.add_argument("--eval_per_epoch", default=10, type=int, help="Do evaluation at every n epochs")
    parser.add_argument("--ckpt", default="None", type=str, help="Checkpoint file")
    parser.add_argument("--optim", default="adam", type=str, help="Optimizer: [adam, sgd]")
    parser.add_argument("--gpu", default="0", type=str)
    parser.add_argument("--eval", default=0, type=int, help="Skip the training step")
    parser.add_argument("--data", default="tvm_data/save_dir/trace_data_all.pkl", type=str, help="The training data")
    parser.add_argument("--w2v_model", default="w2v-new.model", type=str, help="word2vec model")
    parser.add_argument("--type", default="Cropping2D", type=str)
    parser.add_argument("--attr_name", default="cropping", type=str)
    parser.add_argument("--attr_idx", default=0, type=int)
    parser.add_argument("--attention", default=0, type=int)
    parser.add_argument("--shape_info", default=0, type=int)
    parser.add_argument("--num_class", default=9, type=int)
    parser.add_argument("--weight_info", default=0, type=int)
    parser.add_argument("--config_path", default="tvm_data/other_funcs/elf/", type=str)
    parser.add_argument("--log_level", default="INFO", type=str)
    parser.add_argument("--train_ratio", default=0.7, type=float)

    args = parser.parse_args()
    os.environ["CUDA_VISIBLE_DEVICES"] = args.gpu
    run(args)
